<?php

namespace App\Http\Middleware;

use App\User;
use Closure;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;

class ApiAuthorized extends Middleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @param  string|null $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        $apiToken = $request->header('API-TOKEN');
        /** @var User $user */
        $user = User::where("api_token", $apiToken)->first();
        if (!$apiToken || !$user){
            //未授权
            return ['code' => 403, 'msg' => '登录验证失败'];
            //return redirect('api/un-auth');
        }

        if ((time() - $user->last_active_time) > 600){
            //超过十分钟记录一次活跃时间
            $user->last_active_time = time();
            $user->save();
        }

        $request->apiUser = $user;

        return $next($request);
    }
}
